﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;

namespace OrganizedIN.UI.GroupContact
{
    public partial class Group : System.Web.UI.Page
    {
        OIDataContext dc = new OIDataContext();
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                ((Label)Accordion1.FindControl("lblOwnerError")).Text = "";
                ((Label)Accordion2.FindControl("lblError")).Text = "";
                if (!IsPostBack)
                {
                    if (Request["action"] == "Remove" && Request["gid"] != "" && Request["uid"] != "")
                    {
                        var data = (from d in dc.Group_Contact_Mappins
                                    where d.Group_ID == Convert.ToInt32(Request["gid"]) && d.username == Request["uid"]
                                    select d);
                        dc.Group_Contact_Mappins.DeleteAllOnSubmit(data);
                        dc.SubmitChanges();
                        Response.Redirect("Group.aspx", false);
                    }
                    BindGroups();
                    BindMemberGropus();
                    if (Request["index"] != null)
                    {
                        string[] indexes = Request["index"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        Accordion2.SelectedIndex = Convert.ToInt32(indexes[0]);
                        if (indexes.Length > 1)
                        {
                            Accordion1.SelectedIndex = Convert.ToInt32(indexes[1]);
                        }
                    }
                }
            }
            catch (Exception ex) { }
        }

        private void BindGroups()
        {
            var Groups = (from d in dc.Group_Masters where d.User_Organizer_Mapping.username == Session["UserID"].ToString() select new { d.Group_Name, d.Group_ID });
            ((Repeater)Accordion1.FindControl("rptrGroupUsers")).DataSource = Groups;
            ((Repeater)Accordion1.FindControl("rptrGroupUsers")).DataBind();
            ((Repeater)Accordion3.FindControl("rptrOwnerRequest")).DataSource = Groups;
            ((Repeater)Accordion3.FindControl("rptrOwnerRequest")).DataBind();
            string uname = Session["UserID"].ToString();
            var data = (from d in dc.Group_Contact_Mappins
                        where d.username == uname && d.AdminApproved == true && d.Approved == false
                        select new { d.Group_Master.Group_Name, d.Group_ID, Owner = "Owned by " + d.Group_Master.User_Organizer_Mapping.UserInformation.FirstName + " " + d.Group_Master.User_Organizer_Mapping.UserInformation.LastName, d.Group_Master.User_Organizer_Mapping.username, d.GCID });
            ((Repeater)Accordion3.FindControl("rptrMemberRequest")).DataSource = data;
            ((Repeater)Accordion3.FindControl("rptrMemberRequest")).DataBind();
        }

        protected void rptrUsers_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Header && e.Item.ItemType != ListItemType.Footer)
            {
                Repeater rptr = (Repeater)e.Item.FindControl("rptrUsers");
                HiddenField hdn = (HiddenField)e.Item.FindControl("hdnGroupID");
                BindGroupRepeater(rptr, hdn);
            }
        }

        private void BindGroupRepeater(Repeater rptr, HiddenField hdn)
        {
            var owner = (from d in dc.Group_Masters where d.Group_ID == Convert.ToInt32(hdn.Value) select new { Name = d.User_Organizer_Mapping.UserInformation.FirstName + " " + d.User_Organizer_Mapping.UserInformation.LastName, d.User_Organizer_Mapping.username, ProfilePicture = (d.User_Organizer_Mapping.UserInformation.ProfilePicture == null || d.User_Organizer_Mapping.UserInformation.ProfilePicture == "") ? "~/images/user-icon.jpg" : d.User_Organizer_Mapping.UserInformation.ProfilePicture, GroupID = Convert.ToInt32(hdn.Value), IsApproved = true, IsOwner = true }).ToList();
            var data = (from d in dc.Group_Contact_Mappins
                        where d.Group_ID == Convert.ToInt32(hdn.Value) && d.AdminApproved == true
                        select new { Name = d.UserInformation.FirstName + " " + d.UserInformation.LastName, d.username, ProfilePicture = (d.UserInformation.ProfilePicture == null || d.UserInformation.ProfilePicture == "") ? "~/images/user-icon.jpg" : d.UserInformation.ProfilePicture, GroupID = Convert.ToInt32(hdn.Value), IsApproved = d.Approved.Value, IsOwner = false }).ToList();
            owner.AddRange(data);
            rptr.DataSource = owner;
            rptr.DataBind();
        }

        protected void rptrGroupUsers_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            Label l = (Label)e.Item.FindControl("lblError");
            if (e.CommandName == "Delete")
            {
                Group_Master grp = (from g in dc.Group_Masters
                                    where g.Group_ID == Convert.ToInt32(e.CommandArgument)
                                    select g).SingleOrDefault();
                dc.Group_Contact_Mappins.DeleteAllOnSubmit(grp.Group_Contact_Mappins);
                dc.Group_Masters.DeleteOnSubmit(grp);
                dc.SubmitChanges();
                BindGroups();
            }
            if (e.CommandName == "addusers")
            {
                lblOwnerError.Text = "";
                string[] addedcontacts = hdnSelected.Value.Split(new string[] { "||" }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string contact in addedcontacts)
                {
                    if (contact.IndexOf("**" + e.CommandArgument.ToString()) != -1)
                    {
                        string[] gc = contact.Split(new string[] { "**" }, StringSplitOptions.RemoveEmptyEntries);
                        var data = (from g in dc.Group_Contact_Mappins where g.Group_ID.ToString() == gc[1] && g.username == gc[0] select g).SingleOrDefault();
                        if (data == null)
                        {
                            Group_Contact_Mappin gcm = new Group_Contact_Mappin();
                            gcm.username = gc[0];
                            gcm.Group_ID = Convert.ToInt32(gc[1]);
                            gcm.AdminApproved = true;
                            gcm.AdminRejected = false;
                            gcm.AdminRejectionCount = 0;
                            gcm.RejectionCount = 0;
                            gcm.Approved = false;
                            gcm.Rejected = false;
                            dc.Group_Contact_Mappins.InsertOnSubmit(gcm);
                            dc.SubmitChanges();
                            lblOwnerError.ForeColor = Color.Green;
                            lblOwnerError.Text += "Your request has been sent successfully to " + gcm.UserInformation.FirstName + " " + gcm.UserInformation.LastName + " !<br />";

                        }
                        else
                        {
                            if (data.RejectionCount < 3 && data.Rejected == true)
                            {
                                data.AdminRequestDate = DateTime.Now;
                                data.AdminApproved = true;
                                data.AdminRejected = false;
                                data.Approved = false;
                                data.Rejected = false;
                                data.AdminRejectionCount = 0;
                                dc.SubmitChanges();
                                lblOwnerError.ForeColor = Color.Green;
                                lblOwnerError.Text += "Your request has been sent successfully to " + data.UserInformation.FirstName + " " + data.UserInformation.LastName + " !<br />";
                            }
                            else if (data.Rejected == false)
                            {
                                lblOwnerError.ForeColor = Color.Red;
                                lblOwnerError.Text += data.UserInformation.FirstName + " " + data.UserInformation.LastName + " has not reacted to your request yet !<br />";
                            }
                            else
                            {
                                lblOwnerError.ForeColor = Color.Red;
                                lblOwnerError.Text += data.UserInformation.FirstName + " " + data.UserInformation.LastName + " has rejected your requests 3 times so cannot send request again !<br />";
                            }
                        }
                    }
                    BindGroups();
                    hdnSelected.Value = "";
                }
            }
        }

        protected void gvGrps_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "remove")
            {
                var gcm = (from g in dc.Group_Contact_Mappins where g.Group_ID.ToString() == e.CommandArgument.ToString() && g.username == Session["UserID"] select g);
                dc.Group_Contact_Mappins.DeleteAllOnSubmit(gcm);
                dc.SubmitChanges();
                BindMemberGropus();
            }
        }

        private void BindMemberGropus()
        {
            var Groups = (from d in dc.Group_Masters where d.Group_Contact_Mappins.Where(g => g.username == Session["UserID"].ToString() && g.AdminRejected == false && g.Approved == true).Count() > 0 select new { d.Group_Name, d.Group_ID, IsApproved = d.Group_Contact_Mappins.Where(g => g.username == Session["UserID"].ToString()).SingleOrDefault().AdminApproved });
            gvGrps.DataSource = Groups;
            gvGrps.DataBind();
        }

        protected void gvGrps_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Repeater rptr = (Repeater)e.Row.FindControl("rptrUsers");
                HiddenField hdn = (HiddenField)e.Row.FindControl("hdnGroupID");
                BindGroupRepeater(rptr, hdn);
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindRepeater();
        }

        private void BindRepeater()
        {
            string tag = txtSearch.Text.ToLower();
            string uname = Session["UserID"].ToString();
            var data = (from d in dc.Group_Masters
                        where (d.Group_Name.ToLower().IndexOf(tag) != -1)
                        select new { d.Group_Name, d.Group_ID, Owner = "Owned by " + d.User_Organizer_Mapping.UserInformation.FirstName + " " + d.User_Organizer_Mapping.UserInformation.LastName, d.User_Organizer_Mapping.username, IsMember = ((d.Group_Contact_Mappins.Where(a => a.username == uname && a.AdminApproved == true && a.Approved == true).Count() == 0 && d.User_Organizer_Mapping.username != Session["UserID"].ToString()) ? false : true), IsPending = ((d.Group_Contact_Mappins.Where(a => a.username == uname && a.AdminApproved == false && a.Approved == true).Count() == 0 && d.User_Organizer_Mapping.username != Session["UserID"].ToString()) ? false : true) });
            rptrGroups.DataSource = data;
            rptrGroups.DataBind();
        }

        protected void btnAdd_Click(object sender, ImageClickEventArgs e)
        {
            string uname = Session["UserID"].ToString();
            ImageButton ib = (ImageButton)sender;
            if (ib.CommandName == "select")
            {
                var data = (from d in dc.Group_Contact_Mappins
                            where d.Group_ID == Convert.ToInt32(ib.CommandArgument) && d.username == uname
                            select d).SingleOrDefault();
                if (data == null)
                {
                    Group_Contact_Mappin c = new Group_Contact_Mappin();
                    c.username = uname;
                    c.Group_ID = Convert.ToInt32(ib.CommandArgument);
                    c.Approved = true;
                    c.Rejected = false;
                    c.AdminApproved = false;
                    c.AdminRejected = false;
                    c.AdminRejectionCount = 0;
                    c.UserRequestDate = DateTime.Now;
                    dc.Group_Contact_Mappins.InsertOnSubmit(c);
                    dc.SubmitChanges();
                    lblError.ForeColor = Color.Green;
                    lblError.Text = "Your request has been sent successfully !";
                }
                else
                {
                    if (data.AdminRejectionCount < 3)
                    {
                        data.UserRequestDate = DateTime.Now;
                        data.Approved = true;
                        data.AdminApproved = false;
                        data.AdminRejected = false;
                        data.Rejected = false;
                        data.UserRequestDate = DateTime.Now;
                        dc.SubmitChanges();
                        lblError.ForeColor = Color.Green;
                        lblError.Text = "Your request has been sent successfully !";
                    }
                    else
                    {
                        lblError.ForeColor = Color.Red;
                        lblError.Text = "Your requests have been rejected 3 times so cannot send request again !";
                    }
                }
                BindRepeater();
            }
            else if (ib.CommandName == "view")
            {
                Response.Redirect("../Profile/MyProfile.aspx?uid=" + ib.CommandArgument, false);
            }
        }

        protected void rptrOwnerRequest_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Header && e.Item.ItemType != ListItemType.Footer)
            {
                GridView grd = (GridView)e.Item.FindControl("gvOwnerRequests");
                HiddenField hdn = (HiddenField)e.Item.FindControl("hdnReqGroupID");
                BindOwnerGroupRequest(grd, hdn);
            }
        }

        private void BindOwnerGroupRequest(GridView grd, HiddenField hdn)
        {
            var ownerrequests = (from d in dc.Group_Contact_Mappins
                                 where d.Group_ID == Convert.ToInt32(hdn.Value) && d.AdminApproved == false && d.Approved == true
                                 select new { d.GCID, Name = d.UserInformation.FirstName + " " + d.UserInformation.LastName, UserName = d.UserInformation.username, ProfilePicture = (d.UserInformation.ProfilePicture == null || d.UserInformation.ProfilePicture == "") ? "~/images/user-icon.jpg" : d.UserInformation.ProfilePicture, d.UserInformation.Gender, d.UserInformation.DOB });
            grd.DataSource = ownerrequests;
            grd.DataBind();
            grd.RowCommand += new GridViewCommandEventHandler(grdOwnRequest_RowCommand);
        }

        protected void grdOwnRequest_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "confirm")
            {
                var data = (from d in dc.Group_Contact_Mappins
                            where d.GCID == Convert.ToInt64(e.CommandArgument)
                            select d).SingleOrDefault();
                data.RejectionCount = 0;
                data.AdminApproved = true;
                data.JoiningDate = DateTime.Now;
                dc.SubmitChanges();
            }
            else if (e.CommandName == "reject")
            {
                var data = (from d in dc.Group_Contact_Mappins
                            where d.GCID == Convert.ToInt64(e.CommandArgument)
                            select d).SingleOrDefault();
                data.RejectionCount += 1;
                data.Approved = false;
                data.AdminApproved = false;
                data.AdminRejected = true;
                dc.SubmitChanges();
            }
        }

        public bool GetLabelVisibility(object Approved)
        {
            return !(bool)Approved;
        }

        protected void rptrMemberRequest_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            var data = (from d in dc.Group_Contact_Mappins
                        where d.GCID == Convert.ToInt64(e.CommandArgument)
                        select d).SingleOrDefault();
            if (e.CommandName == "confirm")
            {
                data.Approved = true;
                data.AdminApproved = true;
                data.Rejected = false;
                data.AdminRejected = false;
                data.RejectionCount = 0;
                data.AdminRejectionCount = 0;
                data.JoiningDate = DateTime.Now;
                dc.SubmitChanges();
                BindGroups();
                BindMemberGropus();
            }
            else if (e.CommandName == "reject")
            {
                data.Approved = false;
                data.AdminApproved = false;
                data.Rejected = true;
                data.AdminRejected = false;
                data.RejectionCount += 1;
                dc.SubmitChanges();
                BindGroups();
            }
        }
    }
}